<?php

namespace app\components;

/**
 *
 */
class Input
{
    protected $bodyParsed = false;

    /**
     * @param null $name
     * @param mixed $default
     * @return mixed
     */
    public function get($name=null, $default = null)
    {
        if (null === $name) {
            return $_GET + $this->getParsedBody();
        }

        return isset($_GET[$name]) ? $_GET[$name] : $this->post($name, $default);
    }

    /**
     * @param string|null $name
     * @param mixed $default
     * @return mixed
     */
    public function query($name=null, $default = null)
    {
        if (null === $name) {
            return $_GET;
        }

        return isset($_GET[$name]) ? $_GET[$name] : $default;
    }

    /**
     * @param string|null $name
     * @param mixed $default
     * @return mixed
     */
    public function post($name=null, $default = null)
    {
        $body = $this->getParsedBody();

        if (null === $name) {
            return $body;
        }

        return isset($body[$name]) ? $body[$name] : $default;
    }

    /**
     * @return array
     */
    public function getParsedBody()
    {
        if ($this->bodyParsed === false) {
            // post data is json
            if (
                isset($_SERVER['HTTP_CONTENT_TYPE']) &&
                ($type = $_SERVER['HTTP_CONTENT_TYPE']) &&
                strpos($type, '/json') > 0
            ) {
                $this->bodyParsed = json_decode(file_get_contents('php://input'), true);
            } else {
                $this->bodyParsed = &$_POST;
            }
        }

        return $this->bodyParsed;
    }

    /**
     * Get part of it - 获取多个, 可以设置默认值
     * @param array $needKeys
     * $needKeys = [
     *     'name',
     *     'password',
     *     'status' => '1'
     * ]
     * @return array
     */
    public function getMulti(array $needKeys=[])
    {
        $needed = [];

        foreach ($needKeys as $key => $value) {
            if ( is_int($key) ) {
                $needed[$value] = $this->get($value);
            } else {
                $needed[$key] = $this->get($key, $value);
            }
        }

        return $needed;
    }

    public function isCli()
    {
        return PublicHelper::isCli();
    }

    public function isWeb()
    {
        return PublicHelper::isWeb();
    }
}

